package com.blackhorse.topic;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 通配符Topic的交换机类型为：topic
 */
public class Producer {
    public static final String TOPIC_EXCHAGE = "topic_exchange";
    public static final String TOPIC_QUEUE_1 = "topic_queue_1";
    public static final String TOPIC_QUEUE_2 = "topic_queue_2";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(TOPIC_EXCHAGE,//交换机名称
                    BuiltinExchangeType.TOPIC//交换机类型，fanout、topic、topic、headers
            );
            //这里生产者没有创建Queue，可以交给消费者创建，如果消费者也不创建QUEUE，以下消息只会被发送到交换机，然后被丢弃
            //发送消息
            String msg = "新增了商品。Topic模式；routing key 为 item.insert ";
            channel.basicPublish(TOPIC_EXCHAGE, "item.insert", null, msg.getBytes());
            System.out.println("已发送消息：" + msg);
            //发送消息
            msg = "新增了商品。Topic模式；routing key 为 item.update ";
            channel.basicPublish(TOPIC_EXCHAGE, "item.update", null, msg.getBytes());
            System.out.println("已发送消息：" + msg);
            //发送消息
            msg = "新增了商品。Topic模式；routing key 为 item.delete ";
            channel.basicPublish(TOPIC_EXCHAGE, "item.delete", null, msg.getBytes());
            System.out.println("已发送消息：" + msg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtils.close(channel, connection);
        }
    }
}
